/**
 * The contents of this file are subject to the license and copyright detailed in the LICENSE and NOTICE files at the root of the source tree and available online at
 * http://www.askosi.org/license.html
 */
package be.destin.skos.core;

import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class BundleSource {

	/** log4j category */
	private static Logger log = Logger.getLogger(BundleSource.class);

	protected static void load(ConceptScheme aScheme, Properties properties, String configFile, Map<String, String> notationsDefinitions,
			Object sourceApplicationObject) {
		String resourceName = properties.getProperty("resource");
		if (resourceName==null || resourceName.isEmpty()) {
			log.error(aScheme.getAbout() + ": resource=resource-bundle-name must be specified in "+configFile);						
		} else {
			ClassLoader classLoader = null;
			/*if (sourceApplicationObject != null) {
				classLoader = sourceApplicationObject.getClass().getClassLoader();
			}*/
			TermList titles = aScheme.getTitle();
			for (Term nameLang : titles) {
				Locale langLocale = new Locale (nameLang.getLang());
				try {
					ResourceBundle currBundle;
					if (classLoader == null) {
						currBundle = ResourceBundle.getBundle(resourceName, langLocale);
					} else {
						currBundle = ResourceBundle.getBundle(resourceName, langLocale, classLoader);

					}
					Enumeration<String> keys = currBundle.getKeys();
					while (keys.hasMoreElements()) {
						String currCode = keys.nextElement();
						String currAbout = SkosUtil.normalizeAbout(currCode);
						Concept entry = aScheme.findAbout_Concept(currAbout);
						if (entry== null) {
							entry = Concept.ensure(aScheme,currAbout);
							entry = aScheme.putConcept(currAbout, entry);
						}
						entry.putPrefLabel(nameLang.getLang(), null, currBundle.getString(currCode), null, null);
						entry.putUrl(TermList.anyLanguage, currCode);
					}
				} catch (MissingResourceException e) {
					log.error(aScheme.getAbout() + ": MissingResourceException for "+resourceName+": "+e.toString());						

				}
			}
		}
		if (Level.DEBUG.equals(log.getEffectiveLevel())) {
			StringBuffer result=new StringBuffer();
			for (Concept aConcept: aScheme.getConcept()) {
				result.append(aConcept.toString());
				result.append(" -- ");
			}
			log.debug(result.toString());
		}
	}
}
